import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:dulu/sqlite/util.dart';

class MainManager with ChangeNotifier {
  static MainManager instance = MainManager();
  final sqliteUtil = SqliteUtil();
  List allMood = [];

  void init() async {
    // 创建数据库 只会创建一次
    sqliteUtil.createDb(1);
    // clearDb();
    refreshMoodList();
  }

  // 重新查询全部心情记录
  void refreshMoodList() async {
    List res = await queryallMood();
    allMood = res;
    // print(allMood);
    notifyListeners();
  }

  Future queryallMood() async {
    return query("select * from mood");
  }

  // 清空本地mood表
  void clearDb() {
    sqliteUtil.delete("DELETE FROM mood");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  Future queryDayMood(int year, int month, int day) async {
    return sqliteUtil.query(
        "select * from mood where (year,month,day) = ('$year','$month','$day')");
  }

  void insert(int id, int year, int month, int day, int mood, List momt) async {
    final String sqlString =
        "INSERT INTO mood(id,year,month,day,mood,momt) VALUES($id,'$year','$month','$day','$mood','${json.encode(momt)}')";
    await sqliteUtil.insert(sqlString);
    refreshMoodList();
  }

  void updateMood(int id, int mood) async {
    final String sqlString = "UPDATE mood SET mood = ? WHERE id = $id";
    await sqliteUtil.update(sqlString, [mood]);
    refreshMoodList();
  }

  void updateMoodMomt(int id, List momt) async {
    final String sqlString = "UPDATE mood SET momt = ? WHERE id = $id";
    await sqliteUtil.update(sqlString, ['${json.encode(momt)}']);
    refreshMoodList();
  }

  // 根据ID删除心情记录
  void delete(int id) async {
    await sqliteUtil.delete('DELETE FROM mood WHERE id = "$id"');
    refreshMoodList();
  }

  queryMoodFromDate(y, m, d) {
    List matchDataList = allMood.where((item) {
      return item['year'] == y && item['month'] == m && item['day'] == d;
    }).toList();
    return matchDataList.length > 0 ? matchDataList[0] : null;
  }
}
